package cn.edu.zut.internship.web.shiro;


import cn.edu.zut.internship.bean.sys.SysUser;
import cn.edu.zut.internship.entity.AuthSysUser;
import cn.edu.zut.internship.iservice.sys.IUserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {

    @Reference(retries = 0,timeout = 5000)
    private IUserService userService;

    /**
     * @MethodName doGetAuthorizationInfo
     * @Description 权限配置类
     * @Param [principalCollection]
     * @Return AuthorizationInfo
     * @Author WangShiLin
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 已知用户名
//        String username = principalCollection.getPrimaryPrincipal().toString();
        ShiroUser shiroUser = (ShiroUser) principalCollection.getPrimaryPrincipal();
        String username = shiroUser.getUserName();
        //  资源：操作：id     user:create
        List<String> permissionList = userService.getUserPermssions(username);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissionList);

        return simpleAuthorizationInfo;
    }

    /**
     * 身份认证信息
     * 重写该方法，从数据库中获取注册用户和对应的密码，封装成AuthenticationInfo对象返回
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从数据库获取用户的和对应密码，用封装成info返回
        // authenticationToken 当前登录用户的身份标识
        // 已知用户名
        String username = authenticationToken.getPrincipal().toString();
        // 再根据用户名从数据库中找密码
        SysUser sysUser = userService.getSysUserByAccount(username);
        if (sysUser == null) {
            throw new AccountException("account not exist");
        }
        String password = sysUser.getPassword();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, password, this.getName());
        return info;
    }
}

